<template>
  <div>
    <FormItemRest>
      <SelectUser
        :multiple="multiple"
        :selectedIds="selectedIds"
        :key="key"
        @change="
          (ids, options) => {
            emit('update:value', ids.join(','));
            emit('selectedId', ids.join(','));
            emit('change', ids.join(','), options);
          }
        "
        @change-names="
          (names) => {
            userNames = names;
          }
        "
      >
        <a-input
          readonly
          :disabled="disabled"
          :placeholder="placeholder"
          v-model:value="userNames"
          :size="size"
          :bordered="bordered"
        >
          <template #prefix v-if="prefix">
            <Icon :icon="prefix" />
          </template>
          <template #suffix v-if="suffix">
            <Icon :icon="suffix" />
          </template>
        </a-input>
      </SelectUser>
    </FormItemRest>
  </div>
</template>
<script lang="ts" setup>
  import { Form } from 'ant-design-vue';
  import { SelectUser } from '/@/components/SelectOrganizational/index';
  import { watch, ref } from 'vue';
  import { Icon } from '/@/components/Icon';

  // 用于包裹弹窗的form组件 因为一个FormItem 只能收集一个表单组件  所以弹窗的form 必须排除
  const FormItemRest = Form.ItemRest;

  const props = defineProps({
    value: String,
    prefix: String,
    suffix: String,
    placeholder: String,
    readonly: Boolean,
    disabled: Boolean,
    size: String,
    bordered: {
      type: Boolean,
      default: true,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
  });

  const userNames = ref<string>();
  const selectedIds = ref<string[]>([]);
  const emit = defineEmits(['update:value', 'selectedId', 'change']);
  const key = ref<number>(0);

  watch(
    props,
    async () => {
      selectedIds.value = props.value ? props.value?.split(',') : [];
      if (!props.value) {
        //预览页面 重置
        userNames.value = '';
      }
      key.value++;
    },
    {
      immediate: true,
    },
  );
</script>
